<template>
	<div class="app-container">
		<jk-operation-card ref="box1" class="margin-bottom-10">
			<div class="flex-between-center-wrap">
				<div class="flex-start-center-wrap">
					<jk-add-button :permission-prefix="prefix" class="margin-5-0 item-gap" @click="onAddBtn"></jk-add-button>
					<jk-button type="warning" class="item-gap" :has-permission="getPermission([`${prefix}:export`])" size="small" :loading="exportLoading" @click="onReportBtn">导出</jk-button>
				</div>
				<div class="flex-end-center-wrap">
					<jk-date-picker v-model="searchParams.belongDate" placeholder="日期" type="daterange" style="width: 280px;" clearable size="small" class="search-bar-item-size2 margin-5-0 item-gap"></jk-date-picker>
					<jk-search-input v-model="searchParams.code" placeholder="单据编号" size="small" class="search-bar-item-size3 margin-5-0 item-gap" clearable @on-enter="onSearchBtn" />
					<jk-search-button @click="onSearchBtn"></jk-search-button>
				</div>
			</div>
		</jk-operation-card>

		<jk-card>
			<jk-table :loading="tableLoading" :data="tableData" :height="tableHeight + 20">
				<vxe-column
					v-for="(item, index) in tableColumnList"
					:key="index"
					:title="item.title"
					:align="item.align"
					:field="item.keyName"
					:sortable="item.sortable"
					:fixed="item.fixed ? item.fixed : ''"
					:min-width="item.minWidth"
					:width="item.width"
				>
					<template slot-scope="scope">
						<jk-common-status v-if="item.keyName === 'auditState'" :status="scope.row.auditState"></jk-common-status>
						<span v-else-if="item.keyName === 'maxValue'">{{ `${scope.row.minValue}~${scope.row.maxValue}` }}</span>
						<div v-else-if="item.keyName === 'processList'">
							<div
								v-for="(processItem, processIndex) in scope.row.configItem || []"
								:key="processIndex"
							>{{ `${processIndex + 1}、${processItem.processName}: ${processItem.unitPrice}` }}</div>
						</div>
						<span v-else>{{ scope.row[item.keyName] }}</span>
					</template>
				</vxe-column>
				<vxe-column title="操作" align="center" fixed="right" :width="220">
					<template slot-scope="scope">
						<div class="flex-center">
							<jk-button size="mini" icon="el-icon-document-copy" class="item-gap" @click="onCopyBtn(scope.row)"></jk-button>
							<div class="flex-center">
								<jk-button
									class="item-gap"
									:prefix="prefix"
									icon="el-icon-edit"
									:has-permission="getPermission([`${prefix}:update`])"
									size="mini"
									:disabled="scope.row.serviceState === 1 || scope.row.serviceState === 2"
									type="primary"
									@click="onEditBtn(scope.row.id)"
								>编辑</jk-button>
							</div>
							<el-dropdown>
								<jk-button type="primary" size="mini">
									更多<i class="el-icon-arrow-down el-icon--right"></i>
								</jk-button>
								<el-dropdown-menu slot="dropdown">
									<el-dropdown-item
										:disabled="!getPermission([`${prefix}:query`])"
									>
										<div @click="particulars(scope.row.id)">详情</div>
									</el-dropdown-item>
									<el-dropdown-item
										:disabled="!getPermission([`${prefix}:delete`])"
									>
										<div @click="remove(scope.row.id)">删除</div>
									</el-dropdown-item>
								</el-dropdown-menu>
							</el-dropdown>
						</div>
					</template>
				</vxe-column>
			</jk-table>

			<!-- 分页组件 -->
			<footer ref="box2" class="flex-end-center margin-top-10">
				<jk-page
					:page-index="searchParams.pageNo"
					:page-sizes="searchParams.pageSizes"
					:page-size="searchParams.pageSize"
					:total="totalCount"
					@on-change="onPageChange"
				/>
			</footer>
		</jk-card>
		<save-dialog
			:copy="copy"
			:page-type="pageType"
			:data-id="dataId"
			:dialog-state="saveDialogState"
			@on-visible-change="onVisibleChange"
			@on-finish="onFinish"
		></save-dialog>
	</div>
</template>

<script>
    import saveDialog from './save-dialog';
    import calHeight from '/src/mixins/cal-table-height';
    import { formatDate, pageConfig } from '/src/utils/jk/jk-tool';
    import { auditStateList } from '../../../../utils/jk/status-option-list';
    import getMenuColumn from '../../../../mixins/getMenuColumn';
    import { systemUserColumnConfigGet } from '@/api/system/column-config';
    import {
        productionCottonInspectDelete,
        productionCottonInspectPage
    } from '../../../../api/material/inspectionReport';
    import permissionMixin from '../../../../mixins/permission-mixin';

    export default {
        name: 'InspectionReport',
        components: {
            saveDialog
        },
        mixins: [calHeight, getMenuColumn, permissionMixin],
        data() {
            return {
                apiItem: {
                    'page': productionCottonInspectPage,
                    'delete': productionCottonInspectDelete
                },
                pageType: '',
                prefix: 'production:cottonInspect',
                auditStateList: auditStateList,
                dataId: null,
                workshopList: [],
                saveDialogState: false,
                tableLoading: true,
                exportLoading: false,
                tableData: [],
                totalCount: 0,
                processList: [],
                searchParams: {
                    pageNo: pageConfig.pageNo,
                    pageSize: pageConfig.pageSize,
                    belongDate: [],
                    productNameOrCode: '',
                    auditState: null
                },
                isCopy: false,
                copy: false
            };
        },
        mounted() {
            this.getDependentData();
        },
        methods: {
            onCopyBtn(item) {
                this.dataId = item.id;
                this.copy = true;
                this.saveDialogState = true;
            },
            /** 导出按钮操作 */
            onReportBtn() {
                const params = this.searchParams ? JSON.parse(JSON.stringify(this.searchParams)) : {};
                params.pageNo = 1;
                params.pageSize = 500;
                this.$modal.confirm('是否确认导出所有数据数据项?').then(() => {
                    this.exportLoading = true;
                }).then(() => {
                    this.exportLoading = false;
                    return productionCottonInspectPage(params).then(res => {
                        if (res.data.status === 200) {
                  import('@/vendor/Export2Excel').then(excel => {
                    const tHeader = this.tableColumnList.map(x => x.title);
                    const filterVal = this.tableColumnList.map(x => x.keyName);
                    const list = res.data.res ? JSON.parse(JSON.stringify(res.data.res)).map(item => {
                      return item;
                    }) : [];
                    const data = list.map(v => filterVal.map(j => {
                      return v[j];
                    }));
                    excel.export_json_to_excel({
                      header: tHeader,
                      data,
                      filename: `${this.$route.meta.title}`,
                      autoWidth: true,
                      bookType: 'xlsx'
                    });
                  });
                        }
                    });
                }).catch(() => {});
            },
            getMenuColumnListRequest() {
                return systemUserColumnConfigGet({ path: 'InspectionReport', filterShow: true }).then(res => {
                    if (res.data.status === 200) {
                        this.tableColumnList = res.data.res.columnConfigList && res.data.res.columnConfigList.length ? res.data.res.columnConfigList[0].itemList : [];
                    }
                });
            },
            onSearchBtn() {
                this.$set(this.searchParams, 'pageNo', 1);
                this.getListRequest();
            },
            onPageChange(e, size) {
                this.$set(this.searchParams, 'pageNo', e);
                this.$set(this.searchParams, 'pageSize', size);
                this.getListRequest();
            },
            async getDependentData() {
                this.tableLoading = true;
                this.processList = this.$store.state.user.userProcess.processList || [];
                await this.getMenuColumnListRequest();
                await this.getListRequest();
                this.tableLoading = false;
            },
            onDetailBtn(e) {
                this.pageType = 'detail';
                this.dataId = e;
                this.saveDialogState = true;
            },
            onFinish() {
                this.saveDialogState = false;
                this.getListRequest();
            },
            onVisibleChange(e) {
                this.saveDialogState = e;
                if (!e) {
                    this.dataId = null;
                }
            },
            /** 查询列表 */
            getListRequest() {
                this.tableLoading = true;
                return this.apiItem['page'](this.searchParams).then(res => {
                    this.tableLoading = false;
                    if (res.data.status === 200) {
                        this.tableData = res.data.res;
                        this.totalCount = res.data.count;
                    }
                });
            },
            remove(id) {
                this.$confirm('此操作将删除该数据, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    return this.apiItem['delete']({ id: id }).then(res => {
                        this.tableLoading = false;
                        if (res.data.status === 200) {
                            this.getListRequest();
                            this.$message({
                                type: 'success',
                                message: '已删除!'
                            });
                        }
                    });
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消'
                    });
                });
            },
            // 详情
            particulars(id) {
                this.pageType = 'detail';
                this.dataId = id;
                this.saveDialogState = true;
            },
            /** 新增按钮操作 */
            onAddBtn() {
                this.pageType = 'add';
                this.saveDialogState = true;
            },
            /** 修改按钮操作 */
            onEditBtn(row) {
                this.pageType = 'edit';
                this.dataId = row;
                this.saveDialogState = true;
            }
        }
    };
</script>
